<!--
 * @Description: 主要资源配置需求表
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2022-03-18 14:49:52
 * @LastEditTime: 2022-03-29 14:30:23
 * @FilePath: \cscec-pms-admin\src\views\project\plannManagement\plannTableComponents\components\MainResourceAllocation.vue
-->
<template>
  <a-card>
    <title-name title="主要资源配置需求表" />
    <a-button
      v-if="info.pageType !== 'detail'"
      type="primary"
      class="add"
      @click="handleAdd"
    >
      增行
    </a-button>
    <a-button
      v-if="info.pageType !== 'detail'"
      class="add"
      @click="handleDelete"
    >
      删除行
    </a-button>
    <a-table
      ref="table"
      :columns="rColumns"
      :data-source="data"
      :pagination="false"
      bordered
      :loading="loading"
      row-key="id"
      :scroll="{x:width}"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <template
        v-for="(item,key) in estimateDemandList"
        :slot="'estimateDemandTitle'+(key+1)"
      >
        <section
          :key="key"
          class="estimate-demand-title"
        >
          <span>预估需求计划<br>({{ key+1 }}月)</span>
          <template v-if="key+1 === estimateDemandList.length && info.pageType !== 'detail'">
            <a-icon
              v-if="estimateDemandList.length !== 1"
              type="plus"
              class="estimate-demand-del"
              @click="handleDeleteEstimateDemand"
            />
            <a-icon
              v-if="estimateDemandList.length !== 12"
              type="plus"
              class="estimate-demand-add"
              @click="handleAddEstimateDemand"
            />
          </template>
        </section>
      </template>
      <template
        v-for="{dataIndex} in rColumns"
        :slot="dataIndex"
        slot-scope="text,record,index"
      >
        <span :key="dataIndex">
          <!-- 查看 -->
          <template v-if="info.pageType === 'detail'">
            <template v-if="dataIndex === 'planResponsibleId'">
              {{ record.planResponsibleName }}
            </template>
            <template v-else-if="dataIndex === 'supplyResponsibleId'">
              {{ record.supplyResponsibleName }}
            </template>
            <template v-else-if="dataIndex === 'manageResponsibleId'">
              {{ record.manageResponsibleName }}
            </template>
            <template v-else>
              {{ record[dataIndex] }}
            </template>
          </template>
          <!-- 查看 -->
          <template v-else>
            <!-- 预估需求计划 -->
            <BaseInputNumber
              v-if="estimateDemandList.find(el=>el.dataIndex === dataIndex)"
              v-model="record[dataIndex]"
              :precision="2"
              class="input"
              @blur="()=>{handleCalcEstimateTotal(record,index)}"
            />
            <!-- 预估需求计划 -->
            <!-- 资源计划责任人/资源供应责任人/资源管理责任人 -->
            <ASelectOrgPeople
              v-else-if=" ['planResponsibleId','supplyResponsibleId','manageResponsibleId'].includes(dataIndex)"
              :key="dataIndex"
              v-model="record[dataIndex]"
              class="width-100 input"
              @onSelectChange="(v)=>{handleIdChange(v,record,dataIndex,index)}"
            />
            <!-- 资源计划责任人/资源供应责任人/资源管理责任人 -->
            <BaseInput
              v-else
              v-model="record[dataIndex]"
              :class="dataIndex === 'estimateTotal' ? '' : 'input'"
              :max-length="300"
              :disabled="dataIndex === 'estimateTotal'"
            />
          </template>
        </span>
      </template>
    </a-table>
  </a-card>
</template>
<script>
import { scheme } from '@/api/project/plannManagement/plannTableSummary'
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'
export default {
  name: 'MainResourceAllocation' + Date.now(),
  components: {
    ASelectOrgPeople
  },
  data() {
    return {
      // 表头
      columns: [
        {
          title: '序号',
          width: 80,
          align: 'center',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '资源类型',
          dataIndex: 'resourceType',
          align: 'center',
          width: 120,
          scopedSlots: { customRender: 'resourceType' }
        },
        {
          title: '主要资源名称',
          dataIndex: 'name',
          align: 'center',
          width: 120,
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '规格型号',
          dataIndex: 'model',
          align: 'center',
          width: 120,
          scopedSlots: { customRender: 'model' }
        },
        {
          title: '供应方',
          dataIndex: 'supplier',
          align: 'center',
          width: 120,
          scopedSlots: { customRender: 'supplier' }
        },
        {
          title: '预估总量',
          dataIndex: 'estimateTotal',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'estimateTotal' }
        },
        {
          title: '资源计划责任人',
          dataIndex: 'planResponsibleId',
          align: 'center',
          width: 130,
          scopedSlots: { customRender: 'planResponsibleId' }
        },
        {
          title: '资源供应责任人',
          dataIndex: 'supplyResponsibleId',
          align: 'center',
          width: 130,
          scopedSlots: { customRender: 'supplyResponsibleId' }
        },
        {
          title: '资源管理责任人',
          dataIndex: 'manageResponsibleId',
          align: 'center',
          width: 130,
          scopedSlots: { customRender: 'manageResponsibleId' }
        }
      ],
      // 预估需求计划列表
      estimateDemandList: [],
      // 渲染表头
      rColumns: [],
      // 表格宽度
      width: 1130,
      // 表数据
      data: [],
      // 必填项
      required: ['resourceType', 'name', 'model', 'supplier', 'planResponsibleId', 'supplyResponsibleId', 'manageResponsibleId'],
      // 选中项
      selectedRowKeys: [],
      // 加载
      loading: false
    }
  },
  mounted() {
    this.getData()
  },
  computed: {
    // 地址携带信息
    info() {
      return this.$route.query
    }
  },
  methods: {
    /**
     * @description: 获取数据
     * @param {void}
     * @return {void}
     */
    async getData() {
      this.data = []
      const { id, version } = this.info
      this.loading = true
      const { code, data } = await scheme.querySchemeMainResourceDetail({
        latestData: version ? false : true,
        schemeDetailId: id,
        version
      })
      if (code === 200 && data.length > 0) {
        // 已有数据
        this.data = data
        let l = 3
        this.data.forEach((el) => {
          const s = Object.keys(el).filter((item) => item.indexOf('estimateDemand') >= 0 && el[item] !== null).length
          l = s > l ? s : l
        })
        if (l > this.estimateDemandList.length) {
          for (let i = 0; i < l; i++) {
            this.handleAddEstimateDemand()
          }
        }
      } else {
        // 没有数据
        // 默认1-3月预估需求
        if (3 > this.estimateDemandList.length) {
          for (let i = 0; i < 3; i++) {
            this.handleAddEstimateDemand()
          }
        }
        this.handleAdd()
      }
      this.loading = false
    },
    /**
     * @description: 选中项改变
     * @param {string} selectedRowKeys 选中项id
     * @return {void}
     */
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    /**
     * @description: 新增行
     * @param {void}
     * @return {void}
     */
    handleAdd() {
      const data = {}
      this.rColumns.forEach((el) => {
        if (el.dataIndex) {
          if (el.dataIndex === 'resourceType') {
            // 资源类型
            if (this.data.length === 0) {
              data[el.dataIndex] = null
            } else {
              data[el.dataIndex] = this.data[this.data.length - 1][el.dataIndex]
            }
          } else {
            data[el.dataIndex] = null
          }
        } else {
          data.id = 'temp' + Date.now()
        }
      })
      this.data.push(data)
    },
    /**
     * @description: 删除行
     * @param {void}
     * @return {void}
     */
    handleDelete() {
      this.data = this.data.filter((el) => !this.selectedRowKeys.includes(el.id))
      this.selectedRowKeys = []
    },
    /**
     * @description: 删除预估需求计划
     * @param {void}
     * @return {void}
     */
    handleDeleteEstimateDemand() {
      this.estimateDemandList.pop()
      this.width -= 130
      this.required.splice(this.required.indexOf(`estimateDemand${this.estimateDemandList.length + 1}`), 1)
      this.rColumns = [...this.columns.slice(0, 5), ...this.estimateDemandList, ...this.columns.slice(5)]
      this.data.forEach((el, index) => {
        delete el[`estimateDemand${this.estimateDemandList.length + 1}`]
        this.handleCalcEstimateTotal(el, index)
      })
    },
    /**
     * @description: 新增预估需求计划
     * @param {void}
     * @return {void}
     */
    handleAddEstimateDemand() {
      const item = {
        dataIndex: `estimateDemand${this.estimateDemandList.length + 1}`,
        align: 'center',
        width: 130,
        scopedSlots: { title: `estimateDemandTitle${this.estimateDemandList.length + 1}`, customRender: `estimateDemand${this.estimateDemandList.length + 1}` }
      }
      this.estimateDemandList.push(item)
      this.width += 130
      this.required.push(`estimateDemand${this.estimateDemandList.length}`)
      this.rColumns = [...this.columns.slice(0, 5), ...this.estimateDemandList, ...this.columns.slice(5)]
    },
    /**
     * @description: 计算预估总量
     * @param {void} record 行数据
     * @param {number} index 行索引
     * @return {void}
     */
    handleCalcEstimateTotal(record, index) {
      let total = null
      this.estimateDemandList.forEach(({ dataIndex }) => {
        if (typeof record[dataIndex] === 'number') {
          total = total === null ? record[dataIndex] : total.add(record[dataIndex])
        }
      })
      if (total === null) {
        this.$set(this.data, index, { ...record, estimateTotal: null })
      } else {
        this.$set(this.data, index, { ...record, estimateTotal: total })
      }
    },
    /**
     * @description: 表格校验
     * @param {void}
     * @return {boolean} 是否通过校验
     */
    verify() {
      return !this.data.some((el) => {
        for (let item in this.required) {
          if ((el[this.required[item]] ?? '') === '') {
            return true
          }
        }
      })
    },
    /**
     * @description: 保存草稿
     * @param {object} baseInfo 基本信息
     * @return {void}
     */
    MainResourceAllocationSaveDrafts(baseInfo) {
      this.handleSubmit(0, baseInfo)
    },
    /**
     * @description: 提交
     * @param {object} baseInfo 基本信息
     * @return {void}
     */
    MainResourceAllocationSubmit(baseInfo) {
      if (this.verify()) {
        const vm = this
        this.$confirm({
          title: '温馨提示',
          content: '请确认是否提交？',
          onOk() {
            vm.handleSubmit(1, baseInfo)
          }
        })
      } else {
        this.$confirm({
          title: '温馨提示',
          content: '请将数据填写完整'
        })
      }
    },
    /**
     * @description: 数据提交
     * @param {number} status 状态码
     * @return {void}
     */
    handleSubmit(status, baseInfo) {
      const { id: schemeDetailId, pageType } = this.info
      scheme
        .batchUpdateSchemeMainResource({
          changed: pageType === 'change',
          list: this.data,
          schemeDetailId,
          status
        })
        .then(({ code }) => {
          if (code === 200) {
            this.$message.success('操作成功')
            baseInfo.schemeDetailId = schemeDetailId
            baseInfo.status = status
            this.$emit('updateBasicDetail', baseInfo)
            this.getData()
            if (status === 1) {
              this.$close()
            }
          }
        })
    },
    /**
     * @description: 使用单位或项目名称设置
     * @param {object} v 选中项对象
     * @param {object} record 行数据
     * @param {string} dataIndex 列名称
     * @param {number} index 行索引
     * @return {void}
     */
    handleIdChange(v, record, dataIndex) {
      const name = {
        planResponsibleId: 'planResponsibleName',
        supplyResponsibleId: 'supplyResponsibleName',
        manageResponsibleId: 'manageResponsibleName'
      }
      record[name[dataIndex]] = v.name
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.add {
  margin-right: 20px;
  margin-bottom: 20px;
}
@{deep}.input {
  .ant-input,
  .ant-input-number,
  .ant-select-selection {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
}
.width-100 {
  width: 100%;
}
@{deep} .ant-table-header-column {
  width: 100%;
}
.estimate-demand-title {
  position: relative;
  > .anticon-plus {
    position: absolute;
    right: -8px;
    display: block;
  }
  > .estimate-demand-del {
    top: 0;
    transform: rotate(45deg);
  }
  > .estimate-demand-add {
    bottom: 0;
  }
}
</style>
